<?php


namespace app\controller\admin;


use app\model\AdminProblemArticle;
use app\model\AdminProblemType;
use app\util\ReturnCode;
use think\Response;

class ProblemArticle extends Base
{
    /**
     * 获取问题列表
     * @return Response
     * @throws \think\db\exception\DbException
     */
    public function index(): Response {
        $limit = $this->request->get('size', config('apiadmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $keywords = $this->request->get('keywords', '');
        $flag = $this->request->get('flag');
        $problem_type = $this->request->get('problem_type');

        $where['is_delete'] = 0;
        $where['type'] = 1;
        $obj = (new AdminProblemArticle())->hasWhere('type', $where);
        if ($problem_type) {
            $obj->where('problem_id', $problem_type);
        }
        if ($flag) {
            $obj->where('flag', $flag);
        }
        if ($keywords) {
            $obj->whereLike('title', "%{$keywords}%");
        }
        $listObj = $obj->with('type')
            ->append(['flag_text'])
            ->order('create_time', 'DESC')
            ->paginate(['page' => $start, 'list_rows' => $limit])->toArray();

        return $this->buildSuccess([
            'list'  => $listObj['data'],
            'count' => $listObj['total'],
            'type_list' => AdminProblemType::getTypeList(1)
        ]);
    }

    /**
     * 添加问题/反馈类型
     * @return Response
     * @throws \think\db\exception\DbException
     */
    public function add(): Response {
        $postData = $this->request->post();
        $postData['content'] = input('post.content','','htmlspecialchars');
        $res = AdminProblemArticle::create($postData);
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR);
        }

        return $this->buildSuccess();
    }

    /**
     * 编辑问题/反馈类型
     * @return Response
     * @throws \think\db\exception\DbException
     */
    public function edit(): Response {
        $postData = $this->request->post();
        $postData['content'] = input('post.content','','htmlspecialchars');
        $res = AdminProblemArticle::update($postData);
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR);
        }

        return $this->buildSuccess();
    }

    /**
     * 编辑问题/反馈类型
     * @return Response
     * @throws \think\db\exception\DbException
     */
    public function del(): Response {
        $id = $this->request->get('id');
        $res = AdminProblemArticle::destroy($id);
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR);
        }

        return $this->buildSuccess();
    }
}